import os

from dotenv import load_dotenv
from langchain_community.utilities import SQLDatabase

load_dotenv()

"""
数据库连接池封装
"""
class DatabaseConnector:
    __instance = None
    __db = None
    def __new__(cls):
        # 若单例实例不存在，则创建新实例
        if cls.__instance is None:
            cls.__instance = super().__new__(cls)
        return cls.__instance
    def __init__(self):
        if self.__db is None:
            database_username = os.getenv("SQL_USERNAME")
            database_password = os.getenv("SQL_PASSWORD")
            database_host = os.getenv("SQL_HOST")
            database_port = os.getenv("SQL_PORT")
            database_name = os.getenv("SQL_DATABASE")
            self.__db = SQLDatabase.from_uri(
                f"mysql+pymysql://{database_username}:{database_password}@{database_host}:{database_port}/{database_name}"
            )
    async def get_db(self):
        return self.__db